package cmd

import (
	_ "embed"
	"fmt"
	"github.com/spf13/cobra"
	"github.com/xiyoufang/cloud-syncer/internal/util"
	"os"
	"os/exec"
	"runtime"
	"strings"
)

//go:embed default.yml
var defaultYAML string

const configFileName = "cloud-syncer.yml"

var configCmd = &cobra.Command{
	Use:   "config",
	Short: "创建或更新配置文件",
	Run: func(cmd *cobra.Command, args []string) {
		_, err := os.Stat(configFileName)
		if os.IsNotExist(err) {
			file, err := os.Create(configFileName)
			if err != nil {
				fmt.Printf("创建配置文件%s失败, 错误信息: %v\n", configFileName, err)
				return
			}
			defer file.Close()
			secretKey := util.RandomString(64)
			password := util.RandomString(12) // 随机生成一个密码
			defaultYAML = strings.Replace(defaultYAML, "${SYNCER_SECRET_KEY}", secretKey, -1)
			defaultYAML = strings.Replace(defaultYAML, "${SYNCER_PASSWORD}", util.Sha512Hex([]byte(password), []byte(secretKey)), -1)
			_, err = file.WriteString(defaultYAML)
			if err != nil {
				fmt.Printf("配置文件%s写入默认配置失败, 错误信息: %v\n", configFileName, err)
			} else {
				fmt.Printf("网站登录密码为: %s, 如果忘记了请通过`%s password`命令重置\n", password, commandLineName)
			}
		}
		editor := os.Getenv("EDITOR")
		if editor == "" {
			editor = os.Getenv("VISUAL")
		}
		if editor == "" {
			switch runtime.GOOS {
			case "linux":
				editor = "vi" // Linux 默认选择 nano
			case "windows":
				editor = "notepad" // Windows 默认选择 notepad
			case "darwin":
				editor = "vi" // macOS 默认使用 open 命令打开文本编辑器
			}
		}
		vi := exec.Command(editor, configFileName)
		vi.Stdin = os.Stdin
		vi.Stdout = os.Stdout
		vi.Stderr = os.Stderr
		err = vi.Run()
		if err != nil {
			fmt.Printf("打开编辑器错误: %v, 请手动编辑\n", err)
		} else {
			fmt.Println("配置文件更新成功.")
		}
	},
}

func init() {
	rootCmd.AddCommand(configCmd)
}
